package Class013;

public class ImplementStackAndQueue {
    public static void main(String[] args) {
//        myQueue myQueue = new myQueue(3);
        LinkedQueue myQueue = new LinkedQueue(3);
        System.out.println(myQueue.poll());
        myQueue.offer(1);
        myQueue.offer(4);
        System.out.println(myQueue.poll());
        myQueue.offer(5);
        myQueue.offer(6);
        System.out.println(myQueue.peek());
        System.out.println(myQueue.poll());
        myQueue.offer(7);
        System.out.println(myQueue.peek());

    }

    public static class myQueue {
        public int[] queue;
        public int l;
        public int r;

        public myQueue(int max) {
            queue = new int[max];
        }

        public void offer(int val) {
            if(isFull()) {
                System.out.println("Already full");
                return;
            }
            queue[r++] = val;
        }

        public int poll() {
            if(isEmpty()) {
                System.out.println("Already empty");
                return -114514;
            }
            return queue[l++];
        }

        public int peek() {
            if(isEmpty()) {
                System.out.println("Already empty");
                return -114514;
            }
            return queue[l];
        }

        public boolean isEmpty() {
            return l == r;
        }

        public boolean isFull() {
            return r == queue.length;
        }
    }

    //加入一个size记录队列的长度
    //当size < limit,则可以继续添加
    //当size > 0, 则可以弹出
    //否则环形队列需要预留一个空，以区分当前的队列为空还是已满
    public static class LinkedQueue {
        public int[] linkedQueue;
        public int head;
        public int tail;
        public int size;

        public LinkedQueue(int limit) {
            linkedQueue = new int[limit];
        }

        public void offer(int val) {
            if(isFull()) {
                System.out.println("Already Full!");
                return;
            }
            linkedQueue[head] = val;
            head = nextPos(head);
            size++;
        }

        public int poll() {
            if(isEmpty()) {
                System.out.println("Already Empty!");
                return -114514;
            }
            int res = linkedQueue[tail];
            tail = nextPos(tail);
            size--;
            return res;
        }

        public int peek() {
            if(isEmpty()) {
                System.out.println("Already Empty!");
                return -114514;
            }
            return linkedQueue[tail];
        }

        public int nextPos(int cur) {
            return (cur + 1) % linkedQueue.length;
        }

        public boolean isFull() {
            return size == linkedQueue.length;
        }

        public boolean isEmpty() {
            return size == 0;
        }

    }
}
